package com.asm.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.PrecisionModel;

import java.io.IOException;

/**
 * @program: AdvertisementManagementSystem
 * @description:
 * @author: CrysTzj
 * @create: 2019-07-10 09:09
 **/
public class JsonToPointDeserializer extends JsonDeserializer<Point> {
    private final static GeometryFactory GEOMETRY_FACTORY = new GeometryFactory(new PrecisionModel(), 4326);

    @Override
    public Point deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        try {
            String text = jp.getText();
            if (text == null || text.length() <= 0) {
                return null;
            }
            String[] coordinates = text.replaceFirst("POINT ?\\(", "").replaceFirst("\\)", "").split(" ");
            double lat = Double.parseDouble(coordinates[0]);
            double lon = Double.parseDouble(coordinates[1]);
            return GEOMETRY_FACTORY.createPoint(new Coordinate(lat, lon));
        } catch (Exception e) {
            return null;
        }
    }
}
